import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {DialogProvider} from "@providers/dialog";
import {InterfaceProvider} from "@providers/interface";

/*
  Generated class for the NativeSpeechProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class NativeSpeechProvider {

  constructor(public ifp: InterfaceProvider,
              private http: HttpClient,
              private dialog: DialogProvider) {
  }

  /**
   * 获取百度 access_token
   * @param app_id
   * @param app_secret
   * @returns {Promise<any>}
   */
  getAccessToken(): Promise<any> {
    return this.ifp.post({
      interfaceId: 'app.baidu.getAccessToken',
      data: {client_id: 'XnM3VyB2YGIOeycdTDsYWeAr', client_secret: 'a3D1n0eurrdEXjkKztggGWL0xNgFdUwd'}
    }).toPromise()
  }

  /**
   * 文字转语音
   * @param text
   * @returns {Promise<any>}
   */
  text2audio(text): Promise<any> {
    return new Promise<any>((resolve) => {
      alert('11111');
      let text_encode = encodeURI(text);
      let params = {
        text: text_encode || '',
        cuid: 'JL',
        ctp: '1',
        lan: 'zh',
        per: '4',//发音人选择, 0为普通女声，1为普通男生，3为情感合成-度逍遥，4为情感合成-度丫丫，默认为普通女声
        spd: '6',//语速，取值0-15，默认为5中语速
        vol: '10',//音量，取值0-15，默认为5中音量
        pit: '5',//音调，取值0-15，默认为5中语调
        aue: '3'
      };

      this.getAccessToken().then(v => {
        params['tok'] = v['access_token'];
        let body: any = this.buildURLSearchParams(params);
        console.log("https://tsn.baidu.com/text2audio?" + body.toString());
        this.http.get("https://tsn.baidu.com/text2audio?" + body.toString()).toPromise().
        then( vv => {
          const blob = new Blob([vv],{type:"audio/mp3"});
          const blobUrl = URL.createObjectURL(blob);
          resolve(blobUrl);
          alert("获得的数据:" + blobUrl);
        }).catch( e => {
          alert("获取语音错误原因:" + JSON.stringify(e));
          this.dialog.showToast(e);
        });
      }).catch((error)=>{
        this.dialog.showToast("获取accen_token错误原因" + error);
      });

    })

  }

  buildURLSearchParams(paramMap: Map<String, any> | any): URLSearchParams {
    let params = new URLSearchParams;
    for (let key in paramMap) {
      let val = paramMap[key];
      params.set(key, val);
    }
    return params;
  }
}
